package org.jeecg.modules.demo.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.demo.entity.PuContract;
import org.jeecg.modules.demo.demo.service.IPuContractService;
import org.jeecg.modules.demo.pubuyorder.entity.PuBuyOrder;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.utils.ReflectUtil;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;


/**
 * @Description: pu_contract
 * @Author: jeecg-boot
 * @Date:   2021-11-24
 * @Version: V1.0
 */
@Api(tags="pu_contract")
@RestController
@RequestMapping("/demo/puContract")
@Slf4j
public class PuContractController extends JeecgController<PuContract, IPuContractService> {
  @Autowired
  private IPuContractService puContractService;
  @Autowired
  private IPuBuyOrderService puBuyOrderService;
  @Autowired
  private ISoSaleOrderService iSoSaleOrderService;
  @Autowired
  private ISysBaseAPI sysBaseAPI;


  /**
   *
   * @param puContract
   * @param pageNo
   * @param pageSize
   * @param
   * @return
   */
  @AutoLog(value = "采购合同-分页列表查询")
  @ApiOperation(value="采购合同-分页列表查询", notes="采购合同-分页列表查询")
  @GetMapping(value = "/listcg")
  public Result<?> queryPageListCg(@NotNull PuContract puContract,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {

    QueryWrapper<PuContract> queryWrapper = QueryGenerator.initQueryWrapper(puContract, req.getParameterMap());
    String tenantId = req.getHeader("tenant-id");
    String teantName = puBuyOrderService.getTeantName(Integer.parseInt(tenantId));
    queryWrapper.eq("MAISDWMC",teantName);
    if(puContract.getStatus()==null){
      queryWrapper.eq("STATUS",0);
    }
    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
    if(sysUser.getUsername().equals("admin") || sysUser.getUsername().equals("administrator")){
      Page<PuContract> page = new Page<PuContract>(pageNo, pageSize);
      IPage<PuContract> pageList = puContractService.page(page, queryWrapper);
      return Result.OK(pageList);
    }else{
      if(ReflectUtil.isObjectNull(puContract)){
        //queryWrapper.eq("HETLRBH","");
      }
      Page<PuContract> page = new Page<PuContract>(pageNo, pageSize);
      IPage<PuContract> pageList = puContractService.page(page, queryWrapper);
      return Result.OK(pageList);
    }
  }

  /**
   *
   * @param puContract
   * @param pageNo
   * @param pageSize
   * @param req
   * @return
   */
  @AutoLog(value = "销售合同-分页销售列表查询")
  @ApiOperation(value="销售合同-分页列表查询", notes="销售合同-分页列表查询")
  @GetMapping(value = "/listxs")
  public Result<?> queryPageListXs(PuContract puContract,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
    QueryWrapper<PuContract> queryWrapper = QueryGenerator.initQueryWrapper(puContract, req.getParameterMap());
    String tenantId = req.getHeader("tenant-id");
    String teantName = puBuyOrderService.getTeantName(Integer.parseInt(tenantId));
    queryWrapper.eq("CHUMDWMC",teantName);
    if(puContract.getStatus()==null){
      queryWrapper.eq("STATUS",0);
    }
    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
    if(sysUser.getUsername().equals("admin") || sysUser.getUsername().equals("administrator")){
      Page<PuContract> page = new Page<PuContract>(pageNo, pageSize);
      IPage<PuContract> pageList = puContractService.page(page, queryWrapper);
      return Result.OK(pageList);
    }else{
      if(ReflectUtil.isObjectNull(puContract)){
        //queryWrapper.eq("HETLRBH","");
      }
      Page<PuContract> page = new Page<PuContract>(pageNo, pageSize);
      IPage<PuContract> pageList = puContractService.page(page, queryWrapper);
      return Result.OK(pageList);
    }
  }

  /**
   *   添加
   *
   * @param puContract
   * @return
   */
  @AutoLog(value = "pu_contract-添加")
  @ApiOperation(value="pu_contract-添加", notes="pu_contract-添加")
  @PostMapping(value = "/add")
  public Result<?> add(@RequestBody PuContract puContract) {
    puContractService.save(puContract);
    return Result.OK("添加成功！");
  }

  @AutoLog(value = "pu_contract-编辑")
  @ApiOperation(value="pu_contract-编辑", notes="pu_contract-编辑")
  @PutMapping(value = "/editProject")
  public Result<?> editProject(@RequestBody PuContract puContract) {
    puContractService.updateById(puContract);
    return Result.OK("项目选定成功!");
  }


  @PutMapping(value = "/editPuContract")
  public Result<?> editPuContract(@RequestBody PuContract puContract){
    puContractService.updateById(puContract);
    return Result.OK("更新成功!");
  }

  /**
   *  编辑
   *
   * @param puContract
   * @return
   */
  @AutoLog(value = "pu_contract-编辑")
  @ApiOperation(value="pu_contract-编辑", notes="pu_contract-编辑")
  @RequestMapping(value = "/edit",method = RequestMethod.POST)
  public Result<?> edit(@RequestBody PuContract puContract, @RequestParam(name="bbb") String bbb
          , @RequestParam(name="record") String record, HttpServletRequest req) throws ParseException {
    String tenantId = req.getHeader("tenant-id");

    String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();

    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

    puContract = this.puContractService.getById(record);

    List<String> depIds = sysBaseAPI.getDepartIdsByUsername(sysUser.getUsername());
    String dept= null;
    if(depIds.size()>=1){
     dept = depIds.get(0);
    }
    PuBuyOrder puBuyOrder = new PuBuyOrder();


    /**1 采购   2销售*/
    if(bbb.equals("1")){
      String str = puBuyOrderService.getMaxCode();
      Map<String,String> map = new HashMap<>();
      map.put("maxCode",str==null?null:str);
      String name = precode+"CG_";
      String resultCode = generateOddUtil.createCode(map,name);
      //List<DictModel> listdictmodel  = this.iSysDictService.queryDictItemsByCode("tax_rate");
      //Double tax = Double.parseDouble(listdictmodel.get(0).getValue())*0.01;
      puContract.setStatus("1");
      puBuyOrder.setPoCreateDate(new Date());
      puBuyOrder.setPoOrder(resultCode);
//      puBuyOrder.setPoDate(puContract.getCreateTime());
      puBuyOrder.setCreateTime(new Date());
      //puBuyOrder.setPoStaff(sysUser.getId());
      //puBuyOrder.setStaffNo(sysUser.getId());
      puBuyOrder.setPoTotail(BigDecimal.valueOf(puContract.getCustTotal()));
      puBuyOrder.setPuConNo(puContract.getPuConNo());
      puBuyOrder.setShanchu(0);
      puBuyOrder.setShenhe(0);
      puBuyOrder.setZhijian(0);
      puBuyOrder.setPoMin(BigDecimal.valueOf(0));
      puBuyOrder.setPoMax(BigDecimal.valueOf(puContract.getCustTotal()));
      puBuyOrder.setTransport(puContract.getTransport());
      puBuyOrder.setHsdj(puContract.getCustAmount());
      puBuyOrder.setHsje(puContract.getCustAmount()*puContract.getCustTotal());
      puBuyOrder.setHth(puContract.getHetbh());
      puBuyOrder.setWsdj(puContract.getCustAmount()/1.13);
      DecimalFormat df = new DecimalFormat("0.000");
      Double d =Double.parseDouble(df.format(puBuyOrder.getWsdj()));
      puBuyOrder.setWsje(d *puContract.getCustTotal());
      puBuyOrder.setPsTaxrat(13);
      puBuyOrder.setPsTax(BigDecimal.valueOf(puBuyOrder.getHsje()-puBuyOrder.getWsje()));
      puBuyOrder.setZhilzb(puContract.getZhilzb());
      puBuyOrder.setZhilzbjson(puContract.getZhilzbjson());
      puBuyOrder.setUnit(puContract.getUnit());
      puBuyOrder.setMeasureunit(puContract.getUnit());
      puBuyOrder.setCinvname(puContract.getPinp());
      puBuyOrder.setChumdwmc(puContract.getChumdwmc());
      puBuyOrder.setFazbm(puContract.getFazbm());
      puBuyOrder.setDaozbm(puContract.getDaozbm());
      puBuyOrder.setTradecode(puContract.getHetlrbh());
      puBuyOrder.setDepartment(sysUser.getUsername().equals("admin")?null:dept);
      puBuyOrder.setPoStaff(sysUser.getUsername().equals("admin")?null:sysUser.getId());
      puBuyOrder.setDocumentType(0);
      puBuyOrder.setOdlx(0);
      PuBuyOrder puBuyOrdernew = this.puBuyOrderService.getPuBuyOrderByHetbh(puBuyOrder.getPuConNo());
      if(puBuyOrdernew == null){
        this.puBuyOrderService.save(puBuyOrder);
      }
      puContractService.updateById(puContract);
      return Result.OK("生成采购订单成功!");
    }else{
      String str = iSoSaleOrderService.getMaxCode();
      Map<String,String> map = new HashMap<>();
      map.put("maxCode",str==null?null:str);
      String name = precode+"XS_";
      String resultCode = generateOddUtil.createCode(map,name);
      puContract.setStatus("2");
      SoSaleOrder sso = new SoSaleOrder();
      sso.setSoOrder(resultCode);
      sso.setSoConNo(puContract.getHetbh());
      //sso.setStaffNo(sysUser.getId());
//      sso.setSoDate(new Date());
//      sso.setSoEnddate(new Date());
      sso.setPrdNo(puContract.getPinp());
      //sso.setSoStaff(sysUser.getRealname());
      sso.setCreateTime(new Date());
      sso.setSoTotail(BigDecimal.valueOf(puContract.getCustTotal()));
      sso.setSoMin(Double.valueOf(0));
      sso.setSoMax(Double.valueOf(puContract.getCustTotal()));
      sso.setSoCreateDate(new Date());
      sso.setSoStatus(0);
      sso.setIsDelete(0);
      sso.setIsQuality(0);
      sso.setYsType(puContract.getTransport());
      sso.setTarget(puContract.getZhilzb());
      sso.setTargetJson(puContract.getZhilzbjson());
      sso.setDanwei(puContract.getUnit());
      sso.setSl(13);
      sso.setSoCustom(puContract.getMaisdwmc());
      sso.setWsdj(BigDecimal.valueOf(puContract.getCustAmount()/1.13));
      DecimalFormat df = new DecimalFormat("0.000");
      Double d =Double.parseDouble(df.format(sso.getWsdj()));
      sso.setWsje(BigDecimal.valueOf(d*puContract.getCustTotal()));
      sso.setHsdj(BigDecimal.valueOf(puContract.getCustAmount()));
      sso.setHsje(BigDecimal.valueOf(puContract.getCustAmount()*puContract.getCustTotal()));
      sso.setFazbm(puContract.getFazbm());
      sso.setDaozbm(puContract.getDaozbm());
      sso.setTradecode(puContract.getHetlrbh());
      sso.setDept(sysUser.getUsername().equals("admin")?null:dept);
      sso.setSoStaff(sysUser.getUsername().equals("admin")?null:sysUser.getId());
      SoSaleOrder ssonew = this.iSoSaleOrderService.getBySodHetbh(sso.getSoConNo());
      if(ssonew == null){
        iSoSaleOrderService.save(sso);
      }
    }
    puContractService.updateById(puContract);
    return Result.OK("生成订单成功!");
  }

  public static String subStr(String str,int start){
    if(str == null || str.equals("") || str.length() == 0){
      return "";
    }
    if(start<str.length()){
      return str.substring(start);
    }else{
      return "";
    }
  }

  /**
   *   通过id删除
   *
   * @param id
   * @return
   */
  @AutoLog(value = "pu_contract-通过id删除")
  @ApiOperation(value="pu_contract-通过id删除", notes="pu_contract-通过id删除")
  @DeleteMapping(value = "/delete")
  public Result<?> delete(@RequestParam(name="id",required=true) String id) {
    puContractService.removeById(id);
    return Result.OK("删除成功!");
  }

  /**
   *  批量删除
   *
   * @param ids
   * @return
   */
  @AutoLog(value = "pu_contract-批量删除")
  @ApiOperation(value="pu_contract-批量删除", notes="pu_contract-批量删除")
  @DeleteMapping(value = "/deleteBatch")
  public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
    this.puContractService.removeByIds(Arrays.asList(ids.split(",")));
    return Result.OK("批量删除成功!");
  }

  /**
   * 通过id查询
   *
   * @param id
   * @return
   */
  @AutoLog(value = "pu_contract-通过id查询")
  @ApiOperation(value="pu_contract-通过id查询", notes="pu_contract-通过id查询")
  @GetMapping(value = "/queryById")
  public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
    PuContract puContract = puContractService.getById(id);
    if(puContract==null) {
      return Result.error("未找到对应数据");
    }
    return Result.OK(puContract);
  }

  /**
   * 导出excel
   *
   * @param request
   * @param puContract
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, PuContract puContract) {
    return super.exportXls(request, puContract, PuContract.class, "pu_contract");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
    return super.importExcel(request, response, PuContract.class);
  }

}
